const router = require('express').Router()
const validateToken = require('../../../common/validateToken')
const status_code = require('../../../common/status_code')
const db = require('../../../db/async-db')
const { to } = require('await-to-js')
const Bee = require('../../../common/bee/bee')
// 引入发送邮件的模块
const nodemailer = require('nodemailer')
const smtpTransport = require('nodemailer-smtp-transport')

// 创建连接对象
const myMail = '1229263969@qq.com'
const transport = nodemailer.createTransport(
  smtpTransport({
    host: 'smtp.qq.com', // 邮件发送服务器HOST，QQ邮箱为：smtp.qq.com，腾讯企业邮箱：smtp.exmail.qq.com
    port: 465, // smtp端口 默认无需改动 一般为25或465
    secure: true,
    auth: {
      user: myMail, // 用户名
      pass: 'pfqsrhhixafzgjbg', // SMTP授权码
    },
  })
)
// 生成随机验证码函数 及 邮箱验证正则
const randomFns = () => {
  // 生成6位随机数
  let code = ''
  for (let i = 0; i < 6; i++) {
    code += parseInt(Math.random() * 10)
  }
  return code
}
const regEmail =
  /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/ //验证邮箱正则

const codeFailureTime = 1000 * 60

router.post('/send-mail', async (req, resp) => {
  // 错误处理
  function handleError(errCode, error) {
    resp.json({
      code: errCode,
      msg: error ? error : status_code[errCode],
    })
    console.error(error)
  }

  // 清除邮箱验证码 1分钟后失效
  const clearMailCode = (time) => {
    setTimeout(async () => {
      const [updateMailCodeError, updateMailCode] = await to(
        db.query('UPDATE mail_code SET code = ? WHERE mail = ?', ['', e_mail])
      )
      if (updateMailCodeError || !updateMailCode)
        handleError(-1, updateMailCodeError)
    }, time)
  }

  const { e_mail } = req.body

  // 参数错误处理
  if (!regEmail.test(e_mail)) return handleError(10003)

  const [findUserError, findUser] = await to(
    db.query(
      'SELECT * FROM users u INNER JOIN userinfo ui ON u.id = ui.id WHERE ui.mail=?',
      [e_mail]
    )
  )
  // 错误处理
  if (findUserError || !findUser) return handleError(-1, findUserError)
  // 邮箱错误
  if (findUser.length !== 1) return handleError(60011, '邮箱错误')
  const user = findUser[0]

  let code = randomFns()
  console.log(code)
  transport.sendMail(
    {
      from: myMail, // 发件邮箱
      to: e_mail, // 收件列表
      subject: '验证你的电子邮件', // 标题
      html: `
    <p>你好！</p>
    <p>您使用邮箱验证！</p>
    <p>你的验证码是：<strong style="color: #ff4e2a;">${code}</strong></p>
    <p>***该验证码1分钟内有效***</p>`, // html 内容
    },
    async (error, data) => {
      console.log(error)
      if (error) {
        return handleError(-1, '发送验证码错误！')
        transport.close() // 如果没用，关闭连接池
      }
      const [findMailCodeError, findMailCode] = await to(
        db.query('SELECT count(*) FROM mail_code WHERE mail = ?', [e_mail])
      )
      if (findMailCodeError || !findMailCode) handleError(-1, findUserError)
      let count = findMailCode[0]['count(*)']
      console.log(count)
      if (count === 0) {
        const [insertMailCodeError, insertMailCode] = await to(
          db.query(
            'INSERT INTO mail_code (mail, code, created_time, updated_time) VALUES (?, ?, NOW(), NOW())',
            [e_mail, code]
          )
        )
        if (insertMailCodeError || !insertMailCode)
          handleError(-1, insertMailCodeError)
        resp.json({
          code: 0,
          msg: '验证码发送成功',
          data: {
            code_failure_time: codeFailureTime,
          },
        })
        clearMailCode(codeFailureTime) // 清除
        return
      } else {
        const [updateMailCodeError, updateMailCode] = await to(
          db.query(
            'UPDATE mail_code SET code = ?, updated_time=NOW() WHERE mail = ?',
            [code, e_mail]
          )
        )
        if (updateMailCodeError || !updateMailCode)
          handleError(-1, updateMailCodeError)

        resp.json({
          code: 0,
          msg: '验证码发送成功',
          data: {
            code_failure_time: codeFailureTime,
          },
        })
        clearMailCode(codeFailureTime) // 清除
        return
      }
    }
  )

  // return resp.json({
  //   code: 0,
  //   msg: status_code[0],
  //   data: {
  //     list: getCommentSuccess,
  //     total: total,
  //   },
  // })
})

module.exports = router
